<?php
declare(strict_types=1);

namespace WebApp\lib\app;

/**
 * Class Controller
 * @package WebApp\lib
 */
abstract class Controller
{
    /**
     * @var AbstractApp
     */
    protected $app;
    /**
     * @var string
     */
    private $account;
    /**
     * @var string
     */
    private $password;

    public $sessionData = [];
    public $sessionId = '';

    /**
     * Controller constructor.
     * @param AbstractApp $app
     */
    public function __construct($app)
    {
        $this->app = $app;
        $this->init();
    }

    abstract public function init(): void;

    /**
     * @param $account
     * @param $password
     */
    protected function setSessionUser($account, $password)
    {
        $this->app->_SESSION[$this->app->getController() . '-account'] = $account;
        $this->app->_SESSION[$this->app->getController() . '-password'] = $password;
    }

    protected function getSessionUser()
    {
        $this->setAccount($this->hasSession($this->app->getController() . '-account'));
        $this->setPassword($this->hasSession($this->app->getController() . '-password'));
    }

    /**
     * @param $param
     * @throws \Exception
     */
    protected function d($param){
        ob_start();
        echo '<pre>';
        var_dump($param);
        $res = ob_get_contents();
        ob_clean();
        $this->app->getResponse()->end($res);
    }

    /**
     * @param $id
     */
    protected function setId($id){
        $this->app->_SESSION[$this->app->getController() . '-id'] = $id;
    }

    /**
     * @return mixed|string
     */
    protected function getId(){
        return $this->hasSession($this->app->getController() . '-id');
    }

    /**
     * @return mixed
     */
    public function getAccount()
    {
        return $this->account;
    }

    /**
     * @param mixed $account
     */
    public function setAccount($account)
    {
        $this->account = $account;
    }

    /**
     * @return mixed
     */
    public function getPassword()
    {
        return $this->password;
    }

    /**
     * @param mixed $password
     */
    public function setPassword($password)
    {
        $this->password = $password;
    }

    /**
     * @param $key
     * @return string
     */
    public function hasSession($key): string
    {
        return isset($this->app->_SESSION[$key]) ? ($this->app->_SESSION[$key]) : "";
    }

    /**
     * @return ReqProxy
     */
    public function getRequest(){
        return $this->app->getRequest();
    }
}